﻿using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using Rmq.Center;
using User.Api.HttpClients;

namespace Out.TaskRunner.RmqWorkers
{
    public class OrderUnlockingWorker : IWorker
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(OrderUnlockingWorker));

        public void Start(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }

            using (var consumer = new OrderUnlockingConsumer())
            {
                consumer.Subscribe((id, count, dt, msg, channel) =>
                {
                    if (msg.OrderType == OrderType.挂号订单)
                    {
                        return ProcessRegOrder(msg.OrderId, channel);
                    }

                    return new ConsumedResult { Ack = true };
                });

                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }

                    Thread.Sleep(500);
                }
            }
        }

        private ConsumedResult ProcessRegOrder(int orderId, WrapperChannel channel)
        {
            using (var ctx = new HzfyWeiXinEntities())
            {
                var order = ctx.ApptOrder.Where(x => x.Id == orderId).
                    Select(x => new
                    {
                        x.OrderNo,
                        x.RegDate,
                        x.RegType,
                        x.StartTime,
                        x.EndTime,
                        x.CardNo,
                        x.CardType,
                        x.BranchNo,
                        x.RegNo
                    }).FirstOrDefault();
                if (order == null)
                {
                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }

                //执行取消锁号操作
                var unlockRequest = new ExeLockSourceRequest();
                unlockRequest.OrderId = order.OrderNo;
                unlockRequest.RegDate = order.RegDate;
                unlockRequest.RegType = order.BranchNo;
                unlockRequest.StartTime = order.StartTime;
                unlockRequest.EndTime = order.EndTime;
                unlockRequest.CardNo = order.CardNo;
                unlockRequest.CardType = order.CardType;
                unlockRequest.LockQueueNo = order.RegNo;

                ExeLockSourceResponse unlockResponse;
                try
                {
                    var httpClient = InHttpClient.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("HisWs/ExeUnLockSource", unlockRequest).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    unlockResponse = responseMsg.Content.ReadAsAsync<ExeLockSourceResponse>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内取消锁号Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                }


                return new ConsumedResult
                {
                    Ack = true
                };
            }
        }

    }
}